var express = require('express');
var router = express.Router();
var config = require('../config/db')
var mongodb = require('mongodb')
var MongoClient = require('mongodb').MongoClient
var bcrypt = require('bcryptjs')
var jwt = require('jsonwebtoken')
var passport = require('passport')
var path = require("path")
const formidable = require('formidable');

/*登录验证*/
router.post('/login', async function (req, res, next) {
    //获取登录用户的用户名和密码
    let { userName, userPwd } = req.body
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //获取和登录用户名相同的用户数据
    users = await db.collection('user').find({ 'user_name': userName }).toArray()
    // 判断是否存在匹配, 并且密码验证正确的用户数据
    if (users.length > 0 && bcrypt.compareSync(userPwd, users[0].user_pwd)) {
        console.log('123')
        jwt.sign(users[0], 'mykey', { expiresIn: 60 * 60 * 24 }, (err, token) => {
            if (err) {
                res.json({ code: 200, message: 'error:' + err.message });
            } else {
                //返回登陆成功的信息，并返回当前登录用户数据，给前端使用
                res.json({ code: 200, message: 'ok', user: 'Bearer ' + token, data: users[0] });
            }
        })
    } else {
        res.json({ code: 200, message: 'error123' });
    }
});


/* 注册验证 */
router.post('/register', async function (req, res, next) {
    //获取注册用户的用户名和密码
    let { userName, userPwd, userMobile } = req.body
    console.log('req.body:',req.body); 
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //加盐 
    let salt = bcrypt.genSaltSync(10);
    // 加密
    let hash = bcrypt.hashSync(userPwd, salt);
    //创建新用户对象
    let registerUser = {
        // "address": null,
        // "birth": null,
        "user_id": "u001",
        "user_pic": "http://localhost:3000/1.png",
        "user_name": userName,
        "user_pwd": hash,
        "user_sex": true,
        "user_phone": userMobile,
        "role_id": "2",
        // 用户喜好度总计
        // 1文学艺术  2人文社科  3少儿童书  4教育考试  5生活休闲   6经济金融   7默认
        "user_like": "6",
        // 用户最近购书
        // 1文学艺术  2人文社科  3少儿童书  4教育考试  5生活休闲   6经济金融   7默认
        "user_rencent": "6",
        "user_registration":  new Date().toLocaleString()
    }
    let results = await db.collection('user').insertOne(registerUser) //执行添加用户的操作
    console.log('results: ', results)
    //判断用户是否添加成功
    if (results.acknowledged) {
        res.json({
            code: 200, message: 'ok'
        })
    } else {
        res.json({ code: 200, message: 'error' });
    }
})

// /* 修改用户名 */
router.post('/updUserName', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    let { userId, newname } = req.body
    console.log('req.body:',req.body); 
    let client = await MongoClient.connect(config.url)      //获取数据库连接对象
    let db = client.db()
    users = await db.collection('user').find({ '_id': new mongodb.ObjectId(userId) }).toArray() //获取和当前用户id相同的用户数据
    if (users.length > 0) {
        await db.collection('user').updateOne({ '_id': new mongodb.ObjectId(userId) }, { $set: { user_name: newname } })
        res.json({ code: 200, message: 'ok', user: users[0] });
    } else {
        res.json({ code: 200, message: 'no' });
    }

});

//修改密码
router.post('/changePwd', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    let { userId, userOldPwd, userNewPwd } = req.body      // 获取当前用户的id和新旧密码
    console.log('req.body:',req.body)
    let client = await MongoClient.connect(config.url)      //获取数据库连接对象
    let db = client.db()
    users = await db.collection('user').find({ '_id': new mongodb.ObjectId(userId) }).toArray() //获取和当前用户id相同的用户数据
    //判断当前用户的密码和输入原密码是否相同
    if (bcrypt.compareSync(userOldPwd, users[0].user_pwd)) {
        let salt = bcrypt.genSaltSync(10);                      //加盐
        let hash = bcrypt.hashSync(userNewPwd, salt);            //把新密码加密
        //更新旧密码
        let results = await db.collection('user').updateOne({ '_id': new mongodb.ObjectId(userId) }, { $set: { user_pwd: hash } })
        res.json({ code: 200, message: 'ok' });
    } else {
        res.json({ code: 200, message: '旧密码不正确！' });
    }
});

//获取当前登录用户的基本信息
router.get('/getUserInfoById', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    let client = await MongoClient.connect(config.url)      //获取数据库连接对象
    let db = client.db()
    let users = await db.collection('user').find({}).toArray()    //获取所有商品数据
    console.log('user:', users)
    if (users.length > 0) {
        res.json({ code: 200, message: 'ok', data: users });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});


//上传头像
router.post('/uploadHeadPic', passport.authenticate('jwt', { session: false }), function (req, res, next) {
    // 设置上传文件保存的位置
    var dirPath = path.join(__dirname, '..', 'public', 'upload')
    // parse a file upload
    const form = formidable({ multiples: true, uploadDir: dirPath, keepExtensions: true });
    console.log('form:'.form)
    //接受上传的文件和字段,并执行后续的处理
    form.parse(req, async function (err, fields, files) {
        if (err) {
            res.json({ code: 200, message: '上传失败' })
            return;
        }
        //获取上传文件的新名称
        let headpic = files.file.newFilename
        console.log('headpic:', headpic)
        // let userId = fields['userId']
        let userId = req.user._id
        console.log('req:', req)
        // 获取数据库连接对象
        let client = await MongoClient.connect(config.url)
        let db = client.db()
        await db.collection('user').updateOne({ '_id': new mongodb.ObjectId(userId) }, { $set: { user_pic: 'http://localhost:3000/upload/' + headpic } })
        //console.log('fileName: " , headpic.newFilename)3
        res.json({ code: 200, message: 'ok ', data: headpic })
    });
})

module.exports = router;